<template>
  <div class="BigCard">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20" style="padding-bottom:15px">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="Getlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表部分 -->
      <template>
        <el-table :data="userList" border style="width: 100%">
          <el-table-column prop="id" label="#" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="userStateChanged(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.row)"
              ></el-button>
              <!-- 删除 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row)"
              ></el-button>
              <!-- 分配角色 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="handleRoles(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的表单对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- 对话框主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers('addFormRef')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户的表单对话框 -->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
      <el-form ref="formEditDialog" :model="formEdit" :rules="addFormRules">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="formEdit.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="formEdit.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input v-model="formEdit.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加用户的表单对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRoles">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="当前的用户：">{{objRoles.username}}</el-form-item>
        <el-form-item label="当前的角色：">{{objRoles.role_name}}</el-form-item>
        <el-form-item label="分配新角色：">
          <el-select v-model="form.rid" placeholder="请选择活动区域">
            <el-option
              v-for="(item,index) in  roleList"
              :key="index"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleRoles = false">取 消</el-button>
        <el-button type="primary" @click="rolesFormSet">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>      
<script>
import {
  GetList_api,
  exitStatus_api,
  deleteUsers_api,
  addUsers_api,
  editUsers_api,
  rolesAll_api,
  getRoles_api,
} from "../../api/index.js";
import Axios from "axios";
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      // 存分页数据
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      userList: [],
      total: 0,
      // 弹出框操控
      addDialogVisible: false,
      dialogFormVisible: false,
      dialogFormVisibleRoles: false,
      // 编辑数据
      formEdit: {},
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 分配角色
      form: {
        rid: '',
        id: JSON.parse(window.sessionStorage.getItem('user')).id
      },
      objRoles: {},
      roleList: [],
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号码不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 分页功能
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.Getlist();
    },
    handleCurrentChange(current) {
      this.queryInfo.pagenum = current;
      this.Getlist();
    },
    // 获取数据
    async Getlist() {
      const listData = await GetList_api(this.queryInfo);
      this.userList = listData.data.data.users;
      this.total = listData.data.data.total;
    },
    // 用户状态改变
    async userStateChanged(row) {
      const { data: res } = await exitStatus_api(row);
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("修改状态失败");
      }
      this.$message.success("更新状态成功");
    },
    // 删除数据
    async deleteUser(row) {
      const res = await deleteUsers_api(row);
      this.Getlist();
    },
    // 添加用户
    addUsers(addFormRef) {
      this.$refs[addFormRef].validate(async (valid) => {
        if (valid) {
          const res = await addUsers_api(this.addForm);
          this.Getlist();
          this.addDialogVisible = false;
          this.$refs[addFormRef].resetFields();
        } else {
          return false;
        }
      });
    },
    // 修改用户数据
    handleEdit(row) {
      this.formEdit = row;
      this.dialogFormVisible = true;
    },
    resetForm() {
      this.dialogFormVisible = false;
      this.Getlist();
    },
    // 编辑功能
    editUsers() {
      this.$refs.formEditDialog.validate(async (vaide) => {
        if (vaide) {
          const { data: res } = await editUsers_api(this.formEdit);
          this.dialogFormVisible = false;
          this.Getlist();
        } else {
          return;
        }
      });
    },
    async handleRoles(row) {
      this.dialogFormVisibleRoles = true;
      this.objRoles = row;
      const { data: res } = await rolesAll_api();
      this.roleList = res.data;
    },
    async rolesFormSet() {
      const { data: res } = await getRoles_api(this.form);
      console.log(res, 4455);
      this.dialogFormVisibleRoles = false;
      this.Getlist();
    },
  },
  // 创建完后渲染数据
  created() {
    this.Getlist();
  },
};
</script>
<style scoped>
.BigCard {
  width: 100%;
  height: 100%;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  margin-top: 5px;
  width: 100%;
}
</style>